package com.qd.panda.service.third.coupon;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 成都停车平台优惠券接口
 *
 * @author sjk
 * @create 2023-12-12 14:24
 * @since 1.0.0
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class CouponService {

    private static final String GET_COUPON_URL = "/coupon/getcoupon";
    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;

    private static final Map<String, List<String>> MAP = new HashMap<>(1024);

    /**
     * 秘钥key
     */
    @Value("${coupon.key}")
    private String key;
    /**
     * 请求地址
     */
    @Value("${coupon.url}")
    private String url;

    /**
     * 获取优惠券接口
     *
     * @param event 事件
     * @return 优惠券列表
     */
    @SneakyThrows
    public List<String> getCoupon(String event) {
        return test(event);


//        log.info("event: {},key: {}", event, key);
//        String sign = SecureUtil.md5(event + key);
//        log.info("sign: {}", sign);
//        String strResp = restTemplate.getForObject(url + GET_COUPON_URL + "?event=" + event + "&sign=" + sign, String.class);
//        log.info("strResp: {}", strResp);
//        if (StringUtils.hasLength(strResp)) {
//            JsonNode jsonNode = objectMapper.readTree(strResp);
//            int code = jsonNode.get("code").intValue();
//            if (code == 0) {
//                return jsonNode.get("data").findValuesAsText("couponCode");
//            } else {
//                throw new ApiException(jsonNode.get("message").asText());
//            }
//        } else {
//            throw new ApiException("返回值错误");
//        }
    }

    @NotNull
    private static List<String> test(String event) {
        List<String> list = MAP.get(event);
        if(null == list || list .isEmpty()){
            int i = RandomUtil.randomInt(50, 200);
            log.info("优惠券数量: {}", i);
            list = new ArrayList<>(i);
            for (int j = 0; j < i; j++) {
                list.add(RandomUtil.randomString(10));
            }
            MAP.put(event,list);
        }
        return list;
    }

    public boolean isSign(String couponCode, String sign) {
        String newSign = SecureUtil.md5(couponCode + key);
        boolean b = sign.equalsIgnoreCase(newSign);
        log.info("接口传入签名: {},自己签名: {},签名结果: {}", sign, newSign, b);
        return b;
    }
}